
package hk.ces.oxfam.patch.config;

import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;

/**
 *
 * @author ReutyCheng
 */
public enum Config
{
  CLASS_NAME, URL, SCHEMA, USER, PASSWORD;

  public enum ConfigServer
  {
    PRODUCTION, UAT, LOCAL_81, LOCAL_155, LOCAL_4;
  }

  private static final String DEFAULT_DRIVER = "DEFAULT_DRIVER";
  private static final String DRIVER = "DRIVER";
  private static final String IP = "IP";
  private static final String PORT = "PORT";
  private static final String DB_NAME = "DB_NAME";
  private static ConfigServer currentConfigServer = ConfigServer.LOCAL_81;
  
  private final Properties properties = new Properties();

  private Config()
  {
    try
    {
      this.properties.load(this.getClass().getResourceAsStream("/config.properties"));
    }
    catch (IOException ex)
    {
      Logger.getLogger(this.getClass()).error(ex.getMessage(), ex);
      throw new RuntimeException("Can't load db config");
    }
  }

  public static synchronized void setCurrentConfigServer(ConfigServer configServer)
  {
    currentConfigServer = configServer;
  }

  public static ConfigServer getCurrentConfigServer()
  {
    return currentConfigServer;
  }

  private DatabaseDriver getDriver()
  {
    if (this.properties.containsKey(currentConfigServer + "." + DRIVER))
    {
      return DatabaseDriver.valueOf(this.getValue(DRIVER));
    }
    else
    {
      return DatabaseDriver.valueOf(this.properties.getProperty(DEFAULT_DRIVER));
    }
  }

  @Override
  public String toString()
  {
    DatabaseDriver driver = this.getDriver();
    switch (this)
    {
      case CLASS_NAME:
        return driver.getDriverClass();
      case URL:
        return driver.getURLTemplate().replace(getReplacement(IP), getValue(IP)).replace(getReplacement(PORT), getValue(PORT)).replace(getReplacement(DB_NAME), getValue(DB_NAME));
      default:
        return this.getValue(this.name());
    }
  }

  private String getValue(String subKey)
  {
    return this.properties.getProperty(currentConfigServer + "." + subKey);
  }

  public String getReplacement(String subKey)
  {
    return "{" + subKey + "}";
  }
}
